package com.letao.server.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.letao.server.dto.Result;
import com.letao.server.dto.UserAddressDTO;
import com.letao.server.entity.BaseRegion;
import com.letao.server.entity.UserAddress;
import com.letao.server.mapper.UserAddressMapper;
import com.letao.server.service.IBaseRegionService;
import com.letao.server.service.IUserAddressService;
import com.letao.server.utils.RegexUtils;
import com.letao.server.utils.UserHolderUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements IUserAddressService {


    @Resource
    private IBaseRegionService baseRegionService;

    /**
     * 增加地址信息
     *
     * @param address 地址信息
     * @return 返回的结果
     */
    @Override
    public Result insert(UserAddress address) {
        Long userId = UserHolderUtils.getUser().getId();
        UserAddress one = query().eq("user_id", userId).one();
        if (one != null) address.setId(one.getId());
        if (address.getCityId() == null || address.getDetail() == null
                || address.getConsigneeName() == null || address.getConsigneePhoneNumber() == null
                || address.getDistrictId() == null || address.getProvinceId() == null) {
            System.out.println(address);
            return Result.fail("信息不完整");
        }
        address.setUserId(userId);
        if (RegexUtils.isPhoneInvalid(address.getConsigneePhoneNumber())) {
            return Result.fail("手机号码格式错误");
        }
        saveOrUpdate(address);
        return Result.success();
    }

    /**
     * 更新地址信息
     *
     * @param address 地址信息
     * @return 返回的结果
     */
    @Override
    public Result update(UserAddress address) {
        if (address.getConsigneePhoneNumber() != null && RegexUtils.isPhoneInvalid(address.getConsigneePhoneNumber())) {
            return Result.fail("手机号格式错误");
        }
        UserAddress one = query().eq("user_id", UserHolderUtils.getUser().getId()).one();
        address.setUserId(null);
        if (one != null) address.setId(one.getId());
        else address.setUserId(UserHolderUtils.getUser().getId());
        address.setCreateTime(null);
        address.setModifiedTime(null);

        log.debug("{}", address);
        if (address.getProvinceId() == 0) {
            try {
                String[] split = address.getDetail().split(",");
                address.setDetail(split[3]);
                BaseRegion province = baseRegionService.query().like("name", split[0]).eq("level_type", 1).one();
                BaseRegion city = baseRegionService.query().like("name", split[1]).eq("level_type", 2).one();
                BaseRegion district = baseRegionService.query().like("name", split[2]).eq("level_type", 3).one();
                address.setProvinceId(province.getId());
                address.setCityId(city.getId());
                address.setDistrictId(district.getId());
            } catch (Exception e) {
                e.printStackTrace();
                return Result.fail("地址信息格式错误");
            }
        }
        saveOrUpdate(address);
        return Result.success();
    }


    /**
     * 查询地址信息
     *
     * @return 返回的结果
     */
    @Override
    public Result queryAddress() {
        Long userId = UserHolderUtils.getUser().getId();
        UserAddress one = query().eq("user_id", userId).one();
        UserAddressDTO dto = new UserAddressDTO();
        if (one == null) {
            dto.setConsigneeName("");
            dto.setConsigneePhoneNumber("");
            dto.setAddress("");
            dto.setConsigneeSex(3);
            return Result.success(dto);
        }
        dto.setConsigneeName(one.getConsigneeName());
        dto.setConsigneePhoneNumber(one.getConsigneePhoneNumber());
        StringBuilder strBuilder = new StringBuilder();
        BaseRegion province = baseRegionService.getById(one.getProvinceId());
        BaseRegion city = baseRegionService.getById(one.getCityId());
        BaseRegion district = baseRegionService.getById(one.getDistrictId());
        strBuilder.append(province.getName() + ",");
        strBuilder.append(city.getName() + ",");
        strBuilder.append(district.getName() + ",");
        strBuilder.append(one.getDetail());
        dto.setAddress(strBuilder.toString());
        dto.setConsigneeSex(one.getConsigneeSex());
        dto.setProvinceId(one.getProvinceId());
        dto.setCityId(one.getCityId());
        dto.setDistrictId(one.getDistrictId());
        return Result.success(dto);
    }
}
